package com.winning.pmph.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.winning.pmph.entity.ExamKnowledge;
import com.winning.pmph.entity.ExamOutline;
import com.winning.pmph.entity.ExamOutlineDetail;
import com.winning.pmph.mapper.ExamKnowledgeMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Component
@Transactional
public class ExamKnowledgeService extends ServiceImpl<ExamKnowledgeMapper, ExamKnowledge> {
    @Resource
    private ExamBookService examBookService;
    @Resource
    private ExamOutlineService examOutlineService;
    @Resource
    private ExamOutlineDetailService examOutlineDetailService;

    public void saveExamKnowledge(ExamKnowledge examKnowledge) {
        if (examKnowledge.getSource() == ExamKnowledge.SOURCE_TYPE_BOOK) {
            examKnowledge.setSource(ExamKnowledge.SOURCE_TYPE_BOOK);
        } else {
            examKnowledge.setSource(ExamKnowledge.SOURCE_TYPE_NEW);
        }
        saveOrUpdate(examKnowledge);
        // 重新计算知识数量
        updateKnowledgeNum(examKnowledge.getExamOutlineId(), examKnowledge.getExamBookId());
    }

    public void deletedExamKnowledgeById(String ids, String examOutlineId, String examBookId) {
        // 删除对应的知识
        removeByIds(Arrays.asList(ids.split(",")));
        // 重新计算大纲对应的知识数量
        updateKnowledgeNum(examOutlineId, examBookId);
    }

    private void updateKnowledgeNum(String examOutlineId, String examBookId) {
        // 重新计算大纲对应的知识数量
        ExamOutline examOutline = examOutlineService.getById(examOutlineId);
        examOutline.setDetailList(examOutlineDetailService.lambdaQuery().eq(ExamOutlineDetail::getExamOutlineId, examOutlineId).list());
        List<ExamKnowledge> examKnowledgeList = lambdaQuery().eq(ExamKnowledge::getExamBookId, examBookId)
                .isNotNull(ExamKnowledge::getOutlineDetailId).list();
        examBookService.updateKnowledgeNum(examKnowledgeList, examOutline);
    }
}
